package deployr.cli;

import deployr.core.*;
import deployr.domain.*;

public class CreateUpdateWebappResponder extends Responder {

	private final Projects projects;
	private final Workspace workspace;

	public CreateUpdateWebappResponder(Workspace workspace, Projects projects) {
		this.workspace = workspace;
		this.projects = projects;
	}

	@Override
	protected boolean shouldRespond(String method, String requestURI) {
		return "POST".equals(method) && requestURI.matches(".*/updates/.*/webapp.*");
	}

	@Override
	protected Result respondTo(String method, String requestURI, Input input) {
		String updateKey = requestURI.replaceAll(".*/updates/", "").replaceAll("/webapp.*", "");

		IUpdate update = workspace.findUpdate(updateKey);
		if (notFound(update)) return new Result(404);

		Deploy deploy = new Deploy(workspace.getAssets(), update);
		deploy.webappTo(workspace.getWebapps());

		return new Result(200);
	}

}
